package day0221;

public class CloneDemo1 {

    public static void main(String[] args) throws CloneNotSupportedException {
        /*
        浅拷贝： copy 对象和原对象中的引用类型字段是同一个对象（引用）
        深拷贝： 将原对象中的引用类型字段也拷贝一份
         */
        CPU cpu = new CPU();
        cpu.setName("i7-12700H");

        Computer computer = new Computer("ROG 16", cpu);

        Computer clone = computer.getClone();

        System.out.println(computer);
        System.out.println(clone);

        // 原对象的 cpu 改变
        computer.getCpu().setName("i9");

        System.out.println(computer.getCpu().getName());
        System.out.println(clone.getCpu().getName());


    }
}


class CPU {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

class Computer implements Cloneable {

    private String name;

    private CPU cpu;

    public Computer(String name, CPU cpu){
        this.name = name;
        this.cpu = cpu;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public CPU getCpu() {
        return cpu;
    }

    public void setCpu(CPU cpu) {
        this.cpu = cpu;
    }

    public Computer getClone() throws CloneNotSupportedException {
        Object clone = this.clone();
        if (clone instanceof Computer computer) {
            return computer;
        }
        return null;
    }
}
